package edu.yctc.weblog.controller.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.yctc.weblog.constant.RequestAttributes;
import edu.yctc.weblog.constant.TemplatePath;
import edu.yctc.weblog.controller.AdminController;
import edu.yctc.weblog.entity.AdminDO;
import edu.yctc.weblog.entity.ResultDO;
import edu.yctc.weblog.service.AdminService;
import edu.yctc.weblog.service.BlogService;
import edu.yctc.weblog.service.CategoryService;
import edu.yctc.weblog.service.CommentService;
import edu.yctc.weblog.service.LinkService;
import edu.yctc.weblog.service.TagService;
import edu.yctc.weblog.session.SessionContentHolder;
import edu.yctc.weblog.utils.CommonUtils;
import edu.yctc.weblog.vo.AdminSignInVO;
import edu.yctc.weblog.vo.UpdateNameVO;
import edu.yctc.weblog.vo.UpdatePasswordVO;

@Controller("adminController")
@RequestMapping(TemplatePath.S + TemplatePath.ADMIN)
public class AdminControllerImpl implements AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private LinkService linkService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @Override
    @PostMapping(TemplatePath.ADMIN_SIGN_IN)
    public String signIn(@ModelAttribute AdminSignInVO adminSignInVO, HttpSession httpSession) {
        // 入参核验
        if (StringUtils.isBlank(adminSignInVO.getAccount()) || StringUtils.isBlank(adminSignInVO.getPassword())) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, RequestAttributes.MSG_ACCOUNT_PASSWORD_CANNOT_EMPTY);
            return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_SIGN_IN;
        }
        // 核验验证码
        String kaptcha = httpSession.getAttribute("verifyCode") + "";
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(adminSignInVO.getVerifyCode())
            || adminSignInVO.getVerifyCode().equals(kaptcha) == false) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, RequestAttributes.MSG_ERROR_VERIFY_CODE);
            return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_SIGN_IN;
        }
        AdminDO adminDO = new AdminDO();
        adminDO.setPassword(adminSignInVO.getPassword());
        String account = adminSignInVO.getAccount();
        if (CommonUtils.isEmailAddress(account)) {
            adminDO.setEmail(account);
        } else if (CommonUtils.isMobliePhoneNumber(account)) {
            adminDO.setMobile(account);
        }
        // 既不是邮箱也不是手机
        if (StringUtils.isBlank(adminDO.getEmail()) && StringUtils.isBlank(adminDO.getMobile())) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, RequestAttributes.MSG_ERROR_FORMAT);
        }
        ResultDO<AdminDO> resultDO = adminService.signIn(adminDO);
        if (resultDO.isSuccess() == false) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, resultDO.getMsg());
            return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_SIGN_IN;
        }
        SessionContentHolder.addSignInUserId(httpSession.getId(), resultDO.getModule().getId());
        httpSession.setAttribute(RequestAttributes.NIKE_NAME, resultDO.getModule().getNick());
        return "redirect:/" + TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_INDEX;
    }

    @Override
    @GetMapping(TemplatePath.ADMIN_SIGN_IN)
    public String showSignIn() {
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_SIGN_IN;
    }

    @Override
    @GetMapping(TemplatePath.ADMIN_INDEX)
    public String showIndex(HttpServletRequest request) {
        request.setAttribute(RequestAttributes.PATH, RequestAttributes.VALUE_INDEX);
        request.setAttribute(RequestAttributes.CATEGORY_COUNT,
            categoryService.getTotalCategories().getModule().intValue());
        request.setAttribute(RequestAttributes.BLOG_COUNT, blogService.getTotalBlogs().getModule().intValue());
        request.setAttribute(RequestAttributes.LINK_COUNT, linkService.getTotalLinks().getModule().intValue());
        request.setAttribute(RequestAttributes.TAG_COUNT, tagService.getTotalTags().getModule().intValue());
        request.setAttribute(RequestAttributes.COMMENT_COUNT, commentService.getTotalComments().getModule().intValue());
        request.setAttribute(RequestAttributes.PATH, RequestAttributes.VALUE_INDEX);
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_INDEX;
    }

    @Override
    @GetMapping(TemplatePath.ADMIN_PROFILE)
    public String profile(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        Long id = SessionContentHolder.getSignInUserIdBySessionId(sessionId);
        ResultDO<AdminDO> resultDO = adminService.getAdminDOById(id);
        if (resultDO.isSuccess() == false) {
            // 要求登陆
            return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_SIGN_IN;
        }
        AdminDO adminDO = resultDO.getModule();
        request.setAttribute(RequestAttributes.PATH, RequestAttributes.VALUE_PROFILE);
        request.setAttribute(RequestAttributes.LOGIN_USER_NAME, adminDO.getName());
        request.setAttribute(RequestAttributes.NIKE_NAME, adminDO.getNick());
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_PROFILE;
    }

    @Override
    @PostMapping(TemplatePath.ADMIN_PROFILE + TemplatePath.S + TemplatePath.ADMIN_PASSWORD)
    @ResponseBody
    public String updatePassword(HttpServletRequest request, @ModelAttribute UpdatePasswordVO updatePasswordVO) {
        if (StringUtils.isBlank(updatePasswordVO.getOriginalPassword())
            || StringUtils.isBlank(updatePasswordVO.getNewPassword())) {
            return RequestAttributes.MSG_PARAMETER_CANNOT_EMPTY;
        }
        Long id = SessionContentHolder.getSignInUserIdBySessionId(request.getSession().getId());
        ResultDO<Void> resultDO =
            adminService.updatePassword(id, updatePasswordVO.getOriginalPassword(), updatePasswordVO.getNewPassword());
        if (resultDO.isSuccess() == false) {
            return resultDO.getMsg();
        }
        // 清空session数据
        SessionContentHolder.deleteSignInBySessionId(request.getSession().getId());
        request.getSession().removeAttribute(RequestAttributes.ERROR_MSG);
        request.getSession().removeAttribute(RequestAttributes.NIKE_NAME);
        return RequestAttributes.MSG_UPDATE_PASSWORD_SUCCESS;
    }

    @Override
    @PostMapping(TemplatePath.ADMIN_PROFILE + TemplatePath.S + TemplatePath.ADMIN_NAME)
    @ResponseBody
    public String updateName(HttpServletRequest request, @ModelAttribute UpdateNameVO updateNameVO) {
        if (StringUtils.isBlank(updateNameVO.getLoginUserName()) || StringUtils.isBlank(updateNameVO.getNickName())) {
            return RequestAttributes.MSG_PARAMETER_CANNOT_EMPTY;
        }
        Long id = SessionContentHolder.getSignInUserIdBySessionId(request.getSession().getId());
        ResultDO<Void> resultDO =
            adminService.updateName(id, updateNameVO.getLoginUserName(), updateNameVO.getNickName());
        if (resultDO.isSuccess() == false) {
            return resultDO.getMsg();
        }
        request.removeAttribute(RequestAttributes.LOGIN_USER_NAME);
        request.removeAttribute(RequestAttributes.NIKE_NAME);
        request.setAttribute(RequestAttributes.LOGIN_USER_NAME, updateNameVO.getLoginUserName());
        request.setAttribute(RequestAttributes.NIKE_NAME, updateNameVO.getNickName());
        return RequestAttributes.MSG_UPDATE_NAME_SUCCESS;
    }

    @Override
    @GetMapping(TemplatePath.ADMIN_LOGOUT)
    public String logout(HttpServletRequest request) {
        SessionContentHolder.deleteSignInBySessionId(request.getSession().getId());
        request.getSession().removeAttribute(RequestAttributes.ERROR_MSG);
        request.getSession().removeAttribute(RequestAttributes.NIKE_NAME);
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.ADMIN_SIGN_IN;
    }

}
